package com.segersten.othello.service.rest;

import java.io.IOException;
import java.net.URL;
import java.util.Collections;

import org.apache.commons.httpclient.NameValuePair;
import org.mockito.Mockito;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.SubmitMethod;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequestSettings;

public class WebUtil {
	
	public static Page fetchPage(String path, String request, SubmitMethod method)
			throws IOException {
		WebRequestSettings requestSettings = new WebRequestSettings(new URL(
				"http://127.0.0.1:8999" + path), method);

		System.out.println("url: " + requestSettings.getURL());
		if (request == null) {
			System.out.println("" + method + " " + requestSettings.getURL());
		} else {
			System.out.println("" + method + " " + requestSettings.getURL());
			System.out.println("Request " + request);
		}

		if (request != null) {
			requestSettings.setRequestParameters(Collections
					.singletonList(new NameValuePair("reg", request)));
		}

		WebClient webClient = new WebClient();
		Page page = null;
		try {
			page = webClient.getPage(requestSettings);
		} catch (final FailingHttpStatusCodeException e) {
			page = Mockito.mock(Page.class, Mockito.RETURNS_DEEP_STUBS);
			Mockito.when(page.getWebResponse().getStatusCode()).thenReturn(
					e.getStatusCode());
			Mockito.when(page.getWebResponse().getContentAsString())
					.thenReturn(e.getStatusMessage());
		}

		System.out.println("Response code "
				+ page.getWebResponse().getStatusCode());
		System.out.println("Response msg  "
				+ page.getWebResponse().getContentAsString());
		System.out.println("-----------------------");
		return page;
	}
}
